﻿using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;

namespace WP7Client.ServerManager
{
    public class HttpPost
    {
        private Type OTSType;
        private Object OTS;
        public String result;

        public event EventHandler FinishedPost;

        /// <summary>
        /// Maakt een nieuwe HttpWebRequest aan voor een Post.
        /// </summary>
        /// <param name="url">Url van de methode</param>
        /// <param name="otsType">Het type van het object wat men verzend.</param>
        /// <param name="ots">Het te verzenden object</param>
        public HttpPost(String url, Type otsType, Object ots)
        {
            this.OTS = ots;
            this.OTSType = otsType;

            HttpWebRequest req = HttpWebRequest.Create(new Uri(url)) as HttpWebRequest;

            req.Method = "POST";
            req.Accept = "application/json";
            req.AllowReadStreamBuffering = true;
            req.ContentType = "application/json";
            req.BeginGetRequestStream(req_RequestCallback, req);
        }

        private void req_RequestCallback(IAsyncResult result)
        {
            var req = result.AsyncState as HttpWebRequest;

            using (var strm = req.EndGetRequestStream(result))
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(OTSType);
                ser.WriteObject(strm, OTS);
                strm.Flush();
                strm.Close();
            }

            req.BeginGetResponse(req2_RequestCallback, req);
            FinishedPost.Invoke(this, null);
        }

        private void req2_RequestCallback(IAsyncResult result)
        {
            var req = result.AsyncState as HttpWebRequest;
            var resp = req.EndGetResponse(result);
            using (var strm = resp.GetResponseStream())
            {
                using (var reader = new StreamReader(strm))
                {
                    this.result = reader.ReadToEnd();
                }
            }
        }
    }
}
